package cn.how2go.net.server.service;

import cn.how2go.net.server.base.SessionData;
import cn.how2go.net.server.bean.ChannelStatus;
import cn.how2go.net.server.util.DateUtil;
import io.netty.channel.ChannelHandlerContext;

import java.net.InetSocketAddress;
import java.util.Map;

/**
 * Created by Administrator on 2019/7/11.
 */
public class BreakLinkService {

    /**
     * 清理不在线的终端缓存
     */
    public static void clearOffLine(){
        BreakLinkService.clearOffLine(SessionData.BREAKLINKTIME);
    }

    /**
     * 清理不在线的终端缓存
     * @param time 不发送数据时间
     * 单位秒
     */
    public static void clearOffLine(int time){
        if(!SessionData.ALLLINK.isEmpty()) {
            for (Map.Entry<ChannelHandlerContext, ChannelStatus> entry : SessionData.ALLLINK.entrySet()) {
                ChannelStatus bean = entry.getValue();
                //断开已经断开的链接
                try {
                    InetSocketAddress socketAddress = (InetSocketAddress) bean.getCtx().channel().remoteAddress();
                    String ip = "";
                    String port = "";
                    if (socketAddress != null) {
                        ip = socketAddress.getAddress().getHostAddress();
                        port = socketAddress.getPort() + "";
                        if(ip==null ||"".equals(ip) || port==null || "".equals(port)){
                            SessionData.ALLLINK.remove(bean.getCtx());
                        }
                    }else{
                        SessionData.ALLLINK.remove(bean.getCtx());
                    }
                }catch (Exception e){
                    System.out.println("-----------删除已断开链接失败-------"+bean);
                }
                //发送报文后 超时删除 和 乱发报文的终端
                //减轻对无效报文的解析
                if (DateUtil.timepk(bean.getLastSend(), time) || bean.isBad()) {
                    BreakLinkService.removeClient(bean.getCtx());
                    if(bean.getSimno()!=null&& !bean.getSimno().trim().equals("")){
                        //TODO: 修改数据库中设备状态
                    }
                }
            }
        }
    }
    /**
     * 关闭连接，清楚缓存
     */
    private static void removeClient(ChannelHandlerContext ctx){
        ctx.close();
        SessionData.ALLLINK.remove(ctx);
    }

    /**
     * 清楚所有链接缓存
     */
    public static void clearAllLink(){
        if(!SessionData.ALLLINK.isEmpty()) {
            for (Map.Entry<ChannelHandlerContext, ChannelStatus> entry : SessionData.ALLLINK.entrySet()) {
                ChannelStatus bean = entry.getValue();
                removeClient(bean.getCtx());
            }
        }
    }
}
